import { constantRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      // 向后端请求路由数据
      getRouters().then(res => {
        const result = buildmenu(res)
        const accessedRoutes = filterAsyncRouter(result)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  }
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout' || route.component === 'PageView') {
        route.component = Layout
        route.path = '/' + route.path
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}
export const loadView = (view) => { // 路由懒加载
  return () => import(`@/views/${view}`)
}
export function buildmenu(rows) {
  const arr = []
  buildtree(rows, arr, 0)
  return arr
}
export function buildtree(list, arr, parentId) {
  list.forEach(item => {
    if (item.parentId === parentId) {
      var child = {
        name: item.menuName,
        path: item.menuKey,
        meta: { title: item.menuName, icon: item.icon },
        hidden: item.visible === '1',
        alwaysShow: item.parentId === 0,
        component: item.component,
        children: []
      }
      buildtree(list, child.children, item.menuId)
      if (child.children.length === 0) {
        delete child.children
        // delete child.component
      }
      arr.push(child)
    }
  })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
